/**
 * 
 */
package cn.com.callback

import java.util.Map;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;
import cn.com.elite.PropertiesUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * @author ThinkPad
	select groupid,spconditions,customergroup_tablename from customer_group_list gl where refreshfreq=1
	{"groupid":"201810100010","spconditions":"22223334456767","tablename":"customergroup_201810100010","selecttype":1,"runmode":2}
	http://192.168.150.192:8010/EliteGeneralHttpTask/GeneralService/UpdateCustomerGroup
 *
 */
public class UpdateCustomerGroup implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(UpdateCustomerGroup.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
		def batchid,querysql,xmlbody;
		PropertiesUtil properties = new PropertiesUtil();
		def ibqurl = properties.readValue("ibqurl"); //获取webservice接口地址
		def appid = properties.readValue("appid"); //获取appId
		def body = Util.getRequestBody(request,'utf-8'); //获取报文
		try{
			JSONObject obj = JSONObject.fromObject(body); //解析报文		
			def groupid = obj.get("groupid"); //分组编号
			int selecttype = obj.get("selecttype"); //查询数据源 1-安正 2-CRM			
			def spconditions = obj.get("spconditions"); //分组条件
			def tablename = obj.get("tablename"); //分组表名
			def tablename_his = tablename+"_his";
			def runmode = obj.get("runmode"); //运行方式 1自动运行 2手工运行
			log.debug("\n"+"groupid:"+groupid+"\n"+"selecttype:"+selecttype);
			if(groupid.equals("")) {
				return "{\"msg\": \"客户分组不能为空！\",\"code\": -2}"
			}else if (selecttype!=1 && selecttype!=2) {
				return "{\"msg\": \"数据来源不能为空！\",\"code\": -2}"
			}else if(spconditions.equals("")) {
				return "{\"msg\": \"分组条件不能为空！\",\"code\": -2}"
			}else if (tablename.equals("")) {
				return "{\"msg\": \"分组表名不能为空！\",\"code\": -2}"
			}else if (runmode.equals("")) {
				return "{\"msg\": \"运行方式不能为空！\",\"code\": -2}"
			};
			def sqlresult = eliteBean.chaxun_sql("select customgetid('GP') batchid from dual","dataSource");
			batchid = sqlresult[0].get("batchid"); //获取批次号
			def i = 0;			

			def sfundsql='';
			
			//基金名称份额
			String temp_tions ='';
			def sfund='';
			//基金名称交易 --deal_sfund
			String deal_temp_tions ='';
			def deal_sfund='';
			//基金名称账户--ac_sfund
			String ac_temp_tions ='';
			def ac_sfund='';
			
			//基金名称份额
			sfundsql = eliteBean.chaxun_sql("SELECT (select variablevalue from customer_group_condition WHERE groupid='"+groupid+"' AND variablename='var.sfund_id') as variablevalue FROM dual ","dataSource");
			def sfundresult = sfundsql[0].get("variablevalue"); //获取原有值
			sfundsql = eliteBean.chaxun_sql("SELECT COUNT(*) AS SFUND_COUNT FROM CUSTOM_PARAMETER WHERE PARAMETER_TYPE = 'DK_PRODUCT' AND USERFLAG = 1 AND PARAMETER_GROUPID = '10028' AND PARAMETER_ID IN (SELECT REGEXP_SUBSTR ('"+sfundresult+"', '[^,]+', 1,rownum) FROM dual connect by rownum<=LENGTH ('"+sfundresult+"') - LENGTH (regexp_replace('"+sfundresult+"', ',', ''))+1)","dataSource");
			def sfund_count = sfundsql[0].get("SFUND_COUNT"); //判断获取勾选的基金产品是否存在公募
			sfundsql = eliteBean.chaxun_sql("SELECT (select variablevalue from customer_group_condition WHERE groupid='"+groupid+"' AND variablename='var.sfund_t') as variablevalue FROM dual","dataSource");
			def sfund_t = sfundsql[0].get("variablevalue"); //获取是否勾选默认1是0否
			if(sfundresult!=''&&sfundresult!=null&&sfund_t=='1'&&sfund_count>0){
				sfundsql = eliteBean.chaxun_sql("SELECT listagg(PARAMETER_ID,',')within group(order by PARAMETER_ID) as list FROM CUSTOM_PARAMETER WHERE PARAMETER_TYPE = 'DK_PRODUCT' AND USERFLAG = 1 AND PARAMETER_GROUPID = '10028' AND MODIFYBY = 'SYSTEM' AND PARAMETER_ID NOT IN (SELECT PARAMETER_ID FROM FUNDNAME_INFO WHERE FUNDNAME_TYPE = 'sfund' and del_flag =0 AND CUSTLIST_GROUPID ='"+groupid+"')","dataSource");
				def sfundresult_sys = sfundsql[0].get("list"); //获取system值
				if(sfundresult_sys!=''&&sfundresult_sys!=null){
					temp_tions=sfundresult+','+sfundresult_sys;
				}else{
					temp_tions=sfundresult;
				}
				sfund = dealReplace(spconditions, 'BK_PRODUCT:IN:', temp_tions);
			}else{
				sfund=spconditions;
			}
			log.debug("基金名称份额:"+sfund);

			//基金名称交易
			sfundsql= eliteBean.chaxun_sql("SELECT (select variablevalue from customer_group_condition WHERE groupid='"+groupid+"' AND variablename='var.deal_sfund_id') as variablevalue FROM dual ","dataSource");
			def deal_sfundresult = sfundsql[0].get("variablevalue"); //获取原有值
			sfundsql = eliteBean.chaxun_sql("SELECT COUNT(*) AS deal_sfund_count FROM CUSTOM_PARAMETER WHERE PARAMETER_TYPE = 'DK_PRODUCT' AND USERFLAG = 1 AND PARAMETER_GROUPID = '10028' AND PARAMETER_ID IN (SELECT REGEXP_SUBSTR ('"+deal_sfundresult+"', '[^,]+', 1,rownum) FROM dual connect by rownum<=LENGTH ('"+deal_sfundresult+"') - LENGTH (regexp_replace('"+deal_sfundresult+"', ',', ''))+1)","dataSource");
			def deal_sfund_count = sfundsql[0].get("deal_sfund_count"); //判断获取勾选的基金产品是否存在公募
			sfundsql = eliteBean.chaxun_sql("SELECT (select variablevalue from customer_group_condition WHERE groupid='"+groupid+"' AND variablename='var.deal_sfund_t') as variablevalue FROM dual ","dataSource");
			def deal_sfund_t = sfundsql[0].get("variablevalue"); //获取是否勾选默认1是0否
			if(deal_sfundresult!=''&&deal_sfundresult!=null&&deal_sfund_t=='1'&&deal_sfund_count>0){
				sfundsql = eliteBean.chaxun_sql("SELECT listagg(PARAMETER_ID,',')within group(order by PARAMETER_ID) as list FROM CUSTOM_PARAMETER WHERE PARAMETER_TYPE = 'DK_PRODUCT' AND USERFLAG = 1 AND PARAMETER_GROUPID = '10028' AND MODIFYBY = 'SYSTEM' AND PARAMETER_ID NOT IN (SELECT PARAMETER_ID FROM FUNDNAME_INFO WHERE FUNDNAME_TYPE = 'deal_sfund' and del_flag =0 AND CUSTLIST_GROUPID ='"+groupid+"')","dataSource");
				def deal_sfundresult_sys = sfundsql[0].get("list"); //获取system值
				if(deal_sfundresult_sys!=''&&deal_sfundresult_sys!=null){
					deal_temp_tions=deal_sfundresult+','+deal_sfundresult_sys;
				}else{
					deal_temp_tions=deal_sfundresult;
				}
				deal_sfund = dealReplace(sfund, 'BK_PRODUCT_TRAN:IN:', deal_temp_tions);
			}else{
				deal_sfund=sfund;
			}
			log.debug("基金名称交易:"+deal_sfund);

			//基金名称账户
			sfundsql = eliteBean.chaxun_sql("SELECT (select variablevalue from customer_group_condition WHERE groupid='"+groupid+"' AND variablename='var.ac_sfund_id') as variablevalue FROM dual ","dataSource");
			def ac_sfundresult = sfundsql[0].get("variablevalue"); //获取原有值
			sfundsql = eliteBean.chaxun_sql("SELECT COUNT(*) AS ac_sfund_count FROM CUSTOM_PARAMETER WHERE PARAMETER_TYPE = 'DK_PRODUCT' AND USERFLAG = 1 AND PARAMETER_GROUPID = '10028' AND PARAMETER_ID IN (SELECT REGEXP_SUBSTR ('"+ac_sfundresult+"', '[^,]+', 1,rownum) FROM dual connect by rownum<=LENGTH ('"+ac_sfundresult+"') - LENGTH (regexp_replace('"+ac_sfundresult+"', ',', ''))+1)","dataSource");
			def ac_sfund_count = sfundsql[0].get("ac_sfund_count"); //判断获取勾选的基金产品是否存在公募
			sfundsql = eliteBean.chaxun_sql("SELECT (select variablevalue from customer_group_condition WHERE groupid='"+groupid+"' AND variablename='var.ac_sfund_t') as variablevalue FROM dual ","dataSource");
			def ac_sfund_t = sfundsql[0].get("variablevalue"); //获取是否勾选默认1是0否
			if(ac_sfundresult!=''&&ac_sfundresult!=null&&ac_sfund_t=='1'&&ac_sfund_count>0){
				sfundsql = eliteBean.chaxun_sql("SELECT listagg(PARAMETER_ID,',')within group(order by PARAMETER_ID) as list FROM CUSTOM_PARAMETER WHERE PARAMETER_TYPE = 'DK_PRODUCT' AND USERFLAG = 1 AND PARAMETER_GROUPID = '10028' AND MODIFYBY = 'SYSTEM' AND PARAMETER_ID NOT IN (SELECT PARAMETER_ID FROM FUNDNAME_INFO WHERE FUNDNAME_TYPE = 'ac_sfund' and del_flag =0 AND CUSTLIST_GROUPID ='"+groupid+"')","dataSource");
				def ac_sfundresult_sys = sfundsql[0].get("list"); //获取system值
				if(ac_sfundresult_sys!=''&&ac_sfundresult_sys!=null){
					deal_temp_tions=ac_sfundresult+','+ac_sfundresult_sys;
				}else{
					deal_temp_tions=ac_sfundresult;
				}
				
				ac_temp_tions=ac_sfundresult+','+ac_sfundresult_sys;
				ac_sfund = dealReplace(deal_sfund, 'BK_PRODUCT_BAL:IN:', deal_temp_tions);
			}else{
				ac_sfund=deal_sfund;
			}
			log.debug("基金名称账户:"+ac_sfund);
			
			spconditions=ac_sfund;
			log.debug("最终分组条件:"+ac_sfund);

			if(selecttype==1) {
				xmlbody = """
			<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
				<SOAP-ENV:Body>
					<m:executeProcedure xmlns:m="http://service.web.server.ua.businessmatrix.com/">
						<appId>"""+appid+"""</appId>
							<name>s-P_CUST_GROUP</name>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_BATCHID</name>
								<value>"""+batchid+"""</value>
						</params>
						<params>
							<isOutDirectionParam>false</isOutDirectionParam>
							<name>PI_TABLENAME</name>
							<value>"""+tablename+"""</value>
							</params>
							<params>
								<isOutDirectionParam>false</isOutDirectionParam>
								<name>PI_QUERY_STR</name>
								<value>"""+spconditions+"""</value>
						</params>			
					</m:executeProcedure>
				</SOAP-ENV:Body>
			</SOAP-ENV:Envelope>""";
			}else if(selecttype==2) {
				xmlbody = spconditions;
			};	
			querysql = "{call sp_customergroup_deal(?,?,?,?)}";
			def input = new String[3];
			input[0] = batchid;
			input[1] = groupid;
			input[2] = 2;
			
			log.debug("input:"+input);
			def retvalue = eliteBean.executeWithReturn(querysql,input,"dataSource");
			log.debug("调用地址:"+ibqurl);
			log.debug("查询数据源（1安正2CRM）:"+selecttype);
			log.debug("retvalue的值:"+retvalue);
			
			if(selecttype == 1 &&retvalue.equals("1")) {
				
				def result = Util.callWebService(ibqurl,xmlbody,"utf-8","",100000);
				log.debug("调用结果:"+result);
				
				eliteBean.update("update customer_group_synchis set requestdate=sysdate,requeststate=1,requestcontent='"+xmlbody+"' where batch_id='"+batchid+"'","dataSource");
				

			}else if (selecttype == 1 &&retvalue.equals("-1")){
				return "{\"code\":\"-1\",\"msg\":\"接口调用失败！\"}";
			}else{
				log.debug("接口判断条件以上不满足，结束！");
			};
			    return "{\"code\":\"1\",\"msg\":\"接口调用成功，等待后台数据处理！\"}";
			
		}catch (Exception e) {
			log.error("ErrorMessage:",e);
			if(!batchid.equals("")) {
				eliteBean.update("delete from customer_group_synchis where batch_id='"+batchid+"'","dataSource");
			};
			return "{\"code\":\"-1\",\"msg\":\"接口调用失败1！\"}";
		}
		
	}
		public static String dealReplace(String inpString, String inpKey, String inpValue) {

		log.debug("调用参数替换预处理inpString:" + inpString + " inpKey:" + inpKey + " inpValue:" + inpValue);

		String[] inpArray = inpString.split(";");

		if (inpArray.length > 0) {

			List<String> arrList = Arrays.asList(inpArray);

			for (int i = 0; i < arrList.size(); i++) {
				String x = arrList.get(i);
				if (x.indexOf(inpKey) >= 0) {
					if (inpValue != null && inpValue.length() > 0) {
						log.debug("更新值:" + x + "->" + inpKey + inpValue);
						arrList.set(i, inpKey + inpValue);
					} else {
						arrList.remove(i);
						log.debug("删除值...");
					}
				}
			}

			String[] outArray = arrList.toArray(new String[arrList.size()]);

			log.debug("字符串处理成功:" + StringUtils.join(outArray, ";"));
			return StringUtils.join(outArray, ";");

		} else {
			log.debug("字符串处理失败(数组拆分异常)");
			return inpString;
		}
	}
}
